package com.ths.inputservice.video;

import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
//

import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;
import org.videolan.libvlc.util.VLCVideoLayout;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 基于 LibVLC 的 RTSP 播放包装，支持自动重连、低延时参数与简易录像。
 */
public class RtspPlayerManager {
    private final Context context;
    //
    private final Handler handler = new Handler(Looper.getMainLooper());

    private LibVLC libVLC;
    private MediaPlayer mediaPlayer;
    private String currentUrl;
    private Media currentMedia; // 添加媒体引用
    private final AtomicBoolean reconnecting = new AtomicBoolean(false);
    private final AtomicBoolean wantPlay = new AtomicBoolean(false);

    // 添加一个标识，用于记录播放器名称，便于调试和日志
    private String playerName = "unknown";

    private final AtomicBoolean recording = new AtomicBoolean(false);
    private String recordingUrl;

    public RtspPlayerManager(Context context, VLCVideoLayout surfaceView) {
        this(context, surfaceView, "unknown");
    }

    public RtspPlayerManager(Context context, VLCVideoLayout surfaceView, String name) {
        this.playerName = name;
        this.context = context.getApplicationContext();

//        // 初始化LibVLC，使用最小化安全参数
//        ArrayList<String> options = new ArrayList<>();
//        // 使用基本参数，避免初始化错误
//        options.add("--no-audio");
//        options.add("--no-drop-late-frames");
//        options.add("--no-video-title-show");
//        options.add("--network-caching=600");

        ArrayList<String> options = new ArrayList<>();
        options.add("--avcodec-hw=any"); // 尝试硬解
        options.add("--rtsp-tcp"); // 如果是RTSP流，用TCP稳定
        libVLC = new LibVLC(this.context, options);

        mediaPlayer = new MediaPlayer(libVLC);
        attachSurfaceInternal(surfaceView);

        mediaPlayer.setEventListener(event -> {
            switch (event.type) {
                case MediaPlayer.Event.EndReached:
                case MediaPlayer.Event.EncounteredError:
                case MediaPlayer.Event.Stopped:
                    scheduleReconnect();
                    break;
            }
        });
    }

    private void attachSurfaceInternal(VLCVideoLayout sv) {
        try {
            mediaPlayer.detachViews();
        } catch (Exception ignored) {
        }
        // 使用默认视图附加方式
        try {
            mediaPlayer.attachViews(sv, null, false, false);
        } catch (Exception e) {
            // 如果失败，尝试不同的参数
            try {
                mediaPlayer.attachViews(sv, null, true, false);
            } catch (Exception ignored) {
            }
        }
    }

    public void attachSurface(VLCVideoLayout newSurface) {
        attachSurfaceInternal(newSurface);
    }

    public void play(String url) {
        currentUrl = url;
        wantPlay.set(true);

        // 创建新的媒体对象
        Media media = new Media(libVLC, Uri.parse(url));
        // 媒体级别参数配置 - 使用最小化参数，避免崩溃
        // 基本缓存设置
        media.addOption(":network-caching=100");
        // 保存媒体引用
        if (currentMedia != null) {
            currentMedia.release();
        }
        currentMedia = media;

        // 设置媒体并播放
        mediaPlayer.setMedia(media);
        mediaPlayer.play();
    }

    /**
     * 获取当前播放的媒体对象
     */
    public Media getMedia() {
        if (currentMedia != null) {
            // 增加引用计数，防止在外部被意外释放
            currentMedia.retain();
        }
        return currentMedia;
    }

    /**
     * 设置媒体对象并播放
     */
    public void setMedia(Media media) {
        if (media != null) {
            // 停止当前播放
            try {
                mediaPlayer.stop();
            } catch (Exception ignored) {
            }

            // 释放旧媒体
            if (currentMedia != null) {
                currentMedia.release();
            }

            // 设置新媒体
            currentMedia = media;
            currentMedia.retain(); // 增加引用计数

            // 更新URL
            if (media.getUri() != null) {
                currentUrl = media.getUri().toString();
            }

            // 设置媒体并播放
            mediaPlayer.setMedia(media);
            mediaPlayer.play();
            wantPlay.set(true);
        }
    }

    public void stop() {
        wantPlay.set(false);
        try {
            mediaPlayer.stop();
            // 清除媒体，避免后台返回时花屏
            mediaPlayer.setMedia(null);
        } catch (Exception ignored) {
        }
    }

    public void release() {
        stop();
        try {
            mediaPlayer.detachViews();
        } catch (Exception ignored) {
        }

        // 释放媒体资源
        if (currentMedia != null) {
            currentMedia.release();
            currentMedia = null;
        }

        mediaPlayer.release();
        libVLC.release();
    }

    private void scheduleReconnect() {
        if (currentUrl == null) return;
        if (!wantPlay.get()) return; // 用户未期望播放，不重连
        if (reconnecting.getAndSet(true)) return;

        // 使用不同的重连延迟时间，避免两个播放器同时重连可能导致的资源竞争
        int reconnectDelay = playerName.equals("big") ? 1000 : 1500;

        handler.postDelayed(() -> {
            reconnecting.set(false);
            try {
                if (!wantPlay.get()) return;
                play(currentUrl);
            } catch (Exception e) {
                scheduleReconnect();
            }
        }, reconnectDelay);
    }

    private String pendingRecordingPath;

    public void startRecording(File dir) {
        if (recording.get()) return;
        if (currentUrl == null) return;
        recording.set(true);
        pendingRecordingPath = buildDefaultOutFile(dir);
        // 需要重新建 media 以附加 sout
        try {
            mediaPlayer.stop();
        } catch (Exception ignored) {
        }
        play(currentUrl);
    }

    public boolean isRecording() {
        return recording.get();
    }

    public void stopRecording() {
        if (!recording.get()) return;
        recording.set(false);
        pendingRecordingPath = null;
        try {
            mediaPlayer.stop();
        } catch (Exception ignored) {
        }
        // 移除 sout 重新播放
        if (currentUrl != null) play(currentUrl);
    }

    private static String shellEscape(String s) {
        return s;
    }

    private static String buildDefaultOutFile(File dir) {
        String ts = new java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.US).format(new java.util.Date());
        File out = new File(dir, "rec_" + ts + ".ts");
        return out.getAbsolutePath();
    }
}


